package com.cms.recursoshumanos.facade;

import net.rim.device.api.ui.Field;

import com.cms.recursoshumanos.component.ArticuloListButtonField;
import com.cms.recursoshumanos.component.ComidaListButtonField;
import com.cms.recursoshumanos.component.FamiliarListButtonField;
import com.cms.recursoshumanos.handler.ImagenesHandler;
import com.cms.recursoshumanos.transport.BBRequest;
import com.cms.recursoshumanos.transport.BBRequestQueue;
import com.cms.recursoshumanos.transport.HttpRequest;

public class ImagenesFacade extends BaseFacade implements BBRequest.Listener
{

	//private HandlerHomeScreen handler = null;
	private HttpRequest req;
	private String URL = "";
	private Field elField;
	//private ImagenesHandler handlerImgs;
	
	public ImagenesFacade(ImagenesHandler handler, Field elField,String URL)
	{
		//this.handlerImgs = handler;
		this.elField = elField;
		this.URL = URL;
	}
	public void run() 
	{
		enviarSolicitud();
	}
	public void enviarSolicitud() 
	{
		req = new HttpRequest();
		req.setRequestURL(URL);		
        req.setListener(this);
        BBRequestQueue.getInstance().addRequest(req);	
	}

	public void requestCancelled(BBRequest request) 
	{
		
	}

	public void requestFailed(BBRequest request) 
	{
		if (elField instanceof ArticuloListButtonField)
		{
			((ArticuloListButtonField)elField).setFlagBusqueda(true);
		}
		else if (elField instanceof ComidaListButtonField)
		{
			((ComidaListButtonField)elField).setFlagBusqueda(true);
		}
		else if (elField instanceof FamiliarListButtonField)
		{
			((FamiliarListButtonField)elField).setFlagBusqueda(true);
		}
		
	}

	public void requestStarted(BBRequest request) 
	{
		
	}

	public void requestSucceeded(BBRequest request) 
	{
		HttpRequest httpRequest = (HttpRequest) request;
        byte[] dataBytes = httpRequest.getResponseByte();
		carga(dataBytes);
//		CineMarkMain.log("succeeded");
	}
	
	private void carga(byte[] dataBytes) 
	{
		if(elField != null)
		{
			if(elField instanceof ArticuloListButtonField)
			{
				((ArticuloListButtonField)elField).setImagen(dataBytes);
			}
			else if(elField instanceof ComidaListButtonField)
			{
				((ComidaListButtonField)elField).setImagen(dataBytes);
			}
			else if(elField instanceof FamiliarListButtonField)
			{
				((FamiliarListButtonField)elField).setImagen(dataBytes);
			}
			
		}
		
	}
}
